import type { FileMessage } from '../../types';
import { getFileType } from '../../utils';
import { ProgressBar, FileTypeIcon, OcrIcon } from '../UI';
import { useFileUpload, useOcr } from '../../hooks';
import { useState } from 'react';

interface FileMessageProps {
  message: FileMessage;
  isOwn: boolean;
  onDelete?: (messageId: string) => void;
  onCopy?: (content: string) => void;
}

export function FileMessageComponent({ message, isOwn, onDelete, onCopy }: FileMessageProps) {
  const { fileName, fileSize, filePath, uploadProgress, fileHash } = message;
  const fileType = getFileType(fileName);
  const isImage = fileType === 'image';
  const isVideo = fileType === 'video';
  const isUploading = uploadProgress !== undefined && uploadProgress < 100;
  
  // OCR相关状态 - 使用Hook的状态
  const [ocrState, setOcrState] = useState<'idle' | 'processing' | 'completed' | 'error'>('idle');
  const [ocrResult, setOcrResult] = useState<string>('');
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [copied, setCopied] = useState(false);
  
  const { pauseUpload, resumeUpload, cancelUpload, getUploadState } = useFileUpload();
  const { recognizeText, isProcessing: ocrIsProcessing, error: ocrHookError } = useOcr();
  const uploadState = fileHash ? getUploadState(fileHash) : null;
  const isPaused = uploadState?.isPaused || false;
  const hasError = uploadState?.error !== undefined;

  // 统一构建可访问的文件URL（后端基地址 + 相对路径）
  const getAbsoluteUrl = (pathOrUrl?: string): string | null => {
    if (!pathOrUrl) return null;
    if (/^https?:\/\//i.test(pathOrUrl)) return pathOrUrl; // 已经是绝对URL
    const apiBase = (window as any).__API_BASE__ || `${window.location.protocol}//${window.location.hostname}:8001`;
    // 确保只有一个斜杠
    return `${apiBase}${pathOrUrl.startsWith('/') ? pathOrUrl : `/${pathOrUrl}`}`;
  };

  // 同步OCR Hook的状态
  const currentOcrState = ocrIsProcessing ? 'processing' : ocrHookError ? 'error' : ocrState;
  const currentOcrError = ocrHookError?.message || '';

  // 复制文件链接
  const handleCopy = async () => {
    if (filePath && onCopy) {
      const absoluteUrl = getAbsoluteUrl(filePath);
      if (absoluteUrl) {
        onCopy(absoluteUrl);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }
    }
  };

  // 删除消息
  const handleDelete = () => {
    if (onDelete) {
      onDelete(message.id);
      setShowDeleteConfirm(false);
    }
  };
  
  const handleDownload = async () => {
    if (filePath) {
      try {
        // 使用fetch获取文件内容
        const response = await fetch(filePath);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // 创建blob
        const blob = await response.blob();
        
        // 创建blob URL
        const blobUrl = window.URL.createObjectURL(blob);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = fileName;
        link.style.display = 'none';
        
        // 添加到DOM，点击，然后移除
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 清理blob URL
        window.URL.revokeObjectURL(blobUrl);
      } catch (error) {
        console.error('下载文件失败:', error);
        // 如果fetch失败，回退到原来的方法
        const link = document.createElement('a');
        link.href = filePath;
        link.download = fileName;
        link.target = '_blank';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  };
  
  // const getFileExtension = (fileName: string) => {
  //   return fileName.split('.').pop()?.toLowerCase() || '';
  // };
  
  const getStatusText = () => {
    if (hasError) {
      return `上传失败: ${uploadState?.error}`;
    }
    if (isPaused) {
      return isOwn ? `已暂停 ${Math.round(uploadProgress || 0)}%` : `接收中... ${Math.round(uploadProgress || 0)}%`;
    }
    if (isUploading) {
      return isOwn ? `上传中... ${Math.round(uploadProgress || 0)}%` : `接收中... ${Math.round(uploadProgress || 0)}%`;
    }
    return '文件';
  };
  
  const handlePause = () => {
    if (fileHash) {
      pauseUpload(fileHash);
    }
  };
  
  const handleResume = () => {
    if (fileHash) {
      resumeUpload(fileHash);
    }
  };
  
  const handleCancel = () => {
    if (fileHash) {
      cancelUpload(fileHash);
    }
  };

  // OCR文字识别处理
  const handleOcr = async () => {
    if (!filePath || !isImage) return;
    
    try {
      setOcrState('processing');
      
      // 从filePath获取图片文件（使用后端完整地址）
      const absoluteUrl = getAbsoluteUrl(filePath);
      if (!absoluteUrl) throw new Error('无效的文件地址');
      const response = await fetch(absoluteUrl);
      if (!response.ok) {
        throw new Error('无法获取图片文件');
      }
      
      const blob = await response.blob();
      const imageFile = new File([blob], fileName, { type: blob.type });
      
      // 调用真实的OCR API
      const result = await recognizeText(imageFile);
      
      setOcrResult(result.text);
      setOcrState('completed');
    } catch (error) {
      console.error('OCR识别失败:', error);
      setOcrState('error');
    }
  };

  // 复制OCR结果
  
  const handleCopyOcrResult = async () => {
    try {
      await navigator.clipboard.writeText(ocrResult);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error('复制失败:', error);
    }
  };

  // 重新识别
  const handleRetryOcr = () => {
    setOcrState('idle');
    setOcrResult('');
  };

  const formatFileSize = (size: number) => {
    if (size < 1024) return `${size} B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
    return `${(size / (1024 * 1024)).toFixed(1)} MB`;
  };
  
  return (
    <div className="group flex items-start gap-1">
      {/* 自己的消息：按钮在左边 */}
      {isOwn && (
        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity mt-1">
          {/* 删除按钮 */}
          {onDelete && (
            <button
              onClick={() => setShowDeleteConfirm(true)}
              className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-red-50 border border-gray-200 hover:border-red-200 transition-all duration-200"
              title="删除消息"
            >
              <svg className="w-3 h-3 text-gray-500 hover:text-red-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </button>
          )}
          {/* 复制按钮 */}
          {onCopy && filePath && (
            <button
              onClick={handleCopy}
              className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-blue-50 border border-gray-200 hover:border-blue-200 transition-all duration-200"
              title="复制文件链接"
            >
              {copied ? (
                <svg className="w-3 h-3 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              ) : (
                <svg className="w-3 h-3 text-gray-500 hover:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                </svg>
              )}
            </button>
          )}
        </div>
      )}
      
      <div className={`inline-block px-4 py-2 rounded-2xl max-w-xs lg:max-w-md break-words ${
        isOwn
          ? 'bg-gray-100 text-gray-900 rounded-br-md'
          : 'bg-gray-100 text-gray-900 rounded-bl-md'
      }`}>
        
        {/* 文件信息 */}
      {isImage && filePath ? (
        <div className="mb-2 space-y-2">
          <a href={filePath} target="_blank" rel="noreferrer">
            <img
              src={filePath}
              alt={fileName}
              className="max-h-56 rounded-lg object-contain cursor-zoom-in bg-white"
            />
          </a>
          <div className="flex items-center space-x-2">
            <FileTypeIcon fileName={fileName} className="w-5 h-5" />
            <div className="flex-1 min-w-0">
              <button
                onClick={handleDownload}
                className="text-blue-600 underline hover:text-blue-800 font-medium truncate block w-full text-left text-xs"
                title={fileName}
              >
                {fileName}
              </button>
              <div className="text-gray-500 text-xs">{formatFileSize(fileSize)}</div>
            </div>
          </div>
        </div>
      ) : isVideo && filePath ? (
        <div className="mb-2 space-y-2">
          <div className="relative">
            <video
              src={filePath}
              controls
              className="max-h-56 rounded-lg object-contain bg-black"
              preload="metadata"
            >
              您的浏览器不支持视频播放
            </video>
          </div>
          <div className="flex items-center space-x-2">
            <FileTypeIcon fileName={fileName} className="w-5 h-5" />
            <div className="flex-1 min-w-0">
              <button
                onClick={handleDownload}
                className="text-blue-600 underline hover:text-blue-800 font-medium truncate block w-full text-left text-xs"
                title={fileName}
              >
                {fileName}
              </button>
              <div className="text-gray-500 text-xs">{formatFileSize(fileSize)}</div>
            </div>
          </div>
        </div>
      ) : (
        <div className="flex items-center space-x-2 mb-2">
          <FileTypeIcon fileName={fileName} className="w-5 h-5" />
          <div className="flex-1 min-w-0">
            <button
              onClick={handleDownload}
              className="text-blue-600 underline hover:text-blue-800 font-medium truncate block w-full text-left text-xs"
              title={fileName}
            >
              {fileName}
            </button>
            <div className="text-gray-500 text-xs">{formatFileSize(fileSize)}</div>
          </div>
        </div>
      )}

      {/* 状态信息 */}
      <div className="text-gray-600 text-xs mb-2">
        {getStatusText()}
      </div>

      {/* 进度条 */}
      {isUploading && (
        <div className="mb-2">
          <ProgressBar progress={uploadProgress || 0} />
        </div>
      )}

      {/* OCR功能 - 仅对图片文件显示 */}
      {isImage && !isUploading && (
        <div className="mb-3">
          {/* OCR按钮 */}
          {currentOcrState === 'idle' && (
            <button
              onClick={handleOcr}
              className="w-full px-3 py-2 text-xs bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center justify-center space-x-2"
            >
              <OcrIcon className="w-4 h-4" />
              <span>识别图片文字</span>
            </button>
          )}

          {/* OCR处理中 */}
          {currentOcrState === 'processing' && (
            <div className="w-full px-3 py-2 text-xs bg-blue-50 text-blue-700 rounded-lg border border-blue-200 flex items-center justify-center space-x-2">
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"></div>
              <span>正在识别文字...</span>
            </div>
          )}

          {/* OCR结果 */}
          {currentOcrState === 'completed' && (
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium text-green-700 flex items-center space-x-1">
                  <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                  <span>识别完成</span>
                </span>
                <div className="flex space-x-2">
                  <button
                    onClick={handleCopyOcrResult}
                    className={`px-2 py-1 text-xs rounded transition-colors flex items-center space-x-1 ${
                      copied 
                        ? 'bg-green-600 text-white' 
                        : 'bg-green-500 text-white hover:bg-green-600'
                    }`}
                    title="复制识别结果"
                  >
                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={copied ? "M5 13l4 4L19 7" : "M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"} />
                    </svg>
                    <span>{copied ? '已复制' : '复制'}</span>
                  </button>
                  <button
                    onClick={handleRetryOcr}
                    className="px-2 py-1 text-xs bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors flex items-center space-x-1"
                    title="重新识别"
                  >
                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    <span>重新识别</span>
                  </button>
                </div>
              </div>
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
                <pre className="text-xs text-gray-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto leading-relaxed">
                  {ocrResult}
                </pre>
              </div>
            </div>
          )}

          {/* OCR错误 */}
          {currentOcrState === 'error' && (
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium text-red-700 flex items-center space-x-1">
                  <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                  </svg>
                  <span>识别失败</span>
                </span>
                <button
                  onClick={handleRetryOcr}
                  className="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600 transition-colors flex items-center space-x-1"
                  title="重试识别"
                >
                  <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  <span>重试</span>
                </button>
              </div>
              <div className="bg-red-50 border border-red-200 rounded-lg p-2">
                <p className="text-xs text-red-700 flex items-start space-x-1">
                  <svg className="w-3 h-3 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                  </svg>
                  <span>{currentOcrError}</span>
                </p>
              </div>
            </div>
          )}
        </div>
      )}

      {/* 操作按钮 */}
      {isUploading && (
        <div className="flex space-x-2">
          {isPaused ? (
            <button
              onClick={handleResume}
              className="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
            >
              继续
            </button>
          ) : (
            <button
              onClick={handlePause}
              className="px-2 py-1 text-xs bg-yellow-500 text-white rounded hover:bg-yellow-600 transition-colors"
            >
              暂停
            </button>
          )}
          <button
            onClick={handleCancel}
            className="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
          >
            取消
          </button>
        </div>
      )}

      {/* 错误信息 */}
      {hasError && (
        <div className="text-red-500 text-xs mt-2">
          {uploadState?.error}
        </div>
      )}
      </div>
      
      {/* 其他人的消息：按钮在右边 */}
      {!isOwn && (
        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity mt-1">
          {/* 删除按钮 */}
          {onDelete && (
            <button
              onClick={() => setShowDeleteConfirm(true)}
              className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-red-50 border border-gray-200 hover:border-red-200 transition-all duration-200"
              title="删除消息"
            >
              <svg className="w-3 h-3 text-gray-500 hover:text-red-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </button>
          )}
          {/* 复制按钮 */}
          {onCopy && filePath && (
            <button
              onClick={handleCopy}
              className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-blue-50 border border-gray-200 hover:border-blue-200 transition-all duration-200"
              title="复制文件链接"
            >
              {copied ? (
                <svg className="w-3 h-3 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              ) : (
                <svg className="w-3 h-3 text-gray-500 hover:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                </svg>
              )}
            </button>
          )}
        </div>
      )}
      
      {/* 删除确认对话框 */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-4 max-w-xs mx-4">
            <h3 className="text-sm font-medium text-gray-900 mb-2">确认删除</h3>
            <p className="text-xs text-gray-600 mb-3">确定要删除这条消息吗？此操作无法撤销。</p>
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="px-3 py-1.5 text-xs text-gray-600 border border-gray-300 rounded hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleDelete}
                className="px-3 py-1.5 text-xs bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}